var appModule = angular.module('starter.controllers', ['ngIOS9UIWebViewPatch'])
  .controller('CusCtrl', function ($scope, $ionicPopover, $state, CommonUtils, CustomersService, $ionicListDelegate) {
    $scope.$on('$ionicView.beforeEnter', function () {
      CustomersService.getCustomers(function (customers) {
        $scope.customers = customers;
        $scope.sortByName($scope.customers);
      });
    });
    $scope.sortByName = function () {
      if ($scope.customers != null) {
        $scope.customers.sort(function (a, b) {
          return a.cname.localeCompare(b.cname);
        });
      }
    };
    $scope.sortByCompany = function () {
      if ($scope.customers != null) {
        $scope.customers.sort(function (a, b) {
          return a.company.localeCompare(b.company);
        });
      }
    };
    $ionicPopover.fromTemplateUrl('templates/popmenu_sort.html', {
      scope: $scope
    }).then(function (popover) {
      $scope.sortMenu = popover;
    });
    $scope.previewCustomer = function (param) {
      CustomersService.setCurrentCustomer(param);
      CustomersService.loadCard(param);
      CommonUtils.goTo('customer');
    };
    $scope.phoneCall = function (tel) {
      $ionicListDelegate.closeOptionButtons();
      window.open('tel:' + tel, '_system');
    };
    $scope.openWeb = function (url) {
      window.open('http://www.baidu.com', '_blank', 'location=yes');
    };
    $scope.createCustomer = function () {
      CustomersService.resetState();
      CommonUtils.goTo('editCard');
    };
    $scope.showLocation = function (param) {
      CustomersService.setCurrentCustomer(param);
      $ionicListDelegate.closeOptionButtons();
      CommonUtils.goTo('location');
    };
  })
  .controller('CustomerCtrl', function ($scope, CommonUtils, CustomersService) {
    $scope.tab1 = 'templates/customer_detail.html';
    $scope.tab2 = 'templates/customer_record.html';
    $scope.currentTab = $scope.tab1;
    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.currentCustomer = CustomersService.getCurrentCustomer();
    });
    //$scope.goBack = function () {
    //  CommonUtils.goto('tab.cus');
    //};
    $scope.showEditButton = function () {
      return $scope.currentTab === $scope.tab1 && $scope.currentCustomer.userid == $scope.currentCustomer.toUserId;
    };
    $scope.switch = function (tab) {
      $scope.currentTab = tab;
    };
    $scope.edit = function () {
      CommonUtils.goTo('customer-edit');
    };
    $scope.showFavButton = function () {
      return $scope.currentCustomer.isFav == "0";
    };
    $scope.addToFav = function (cids) {
      CommonUtils.showLoadingDialog("请在请求");
      CustomersService.addToFav(cids, function (data) {
        $scope.currentCustomer.isFav = '1';
        CommonUtils.hideLoadingDialog();
      });
    };
  })
  .controller('CustomerEditCtrl', function ($scope, $state, CommonUtils, CustomersService, $ionicListDelegate) {
    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.currentCustomer = CustomersService.getCurrentCustomer();
      $scope.getShareInfo();
    });
    $scope.goSharePer = function () {
      action = "sharePer";
      $state.go('contacts', {action: JSON.stringify(action)});
    };
    $scope.goShareDep = function () {
      $state.go('Orgs');
    };
    $scope.editCard = function (card) {
      CustomersService.setCurrentCard(card);
      CommonUtils.goTo('editCard');
    };
    $scope.addCard = function () {
      CustomersService.addCardState();
      CommonUtils.goTo('editCard');
    };
    $scope.departmentLabel = '';
    $scope.shareUserLabel = '';
    $scope.showShareOption = function () {
      return $scope.currentCustomer.hasLoadShareInfo;
    };
    $scope.getShareInfo = function () {
      if ($scope.currentCustomer.id) {
        CustomersService.getShareInfo($scope.currentCustomer.id, function (data) {
          $scope.currentCustomer.departments = data.departments;
          $scope.currentCustomer.users = data.users;
          if ($scope.currentCustomer.departments && $scope.currentCustomer.departments.length > 0) {
            $scope.departmentLabel = $scope.currentCustomer.departments[0].orgname + '等';
          }
          if ($scope.currentCustomer.users && $scope.currentCustomer.users.length > 0) {
            $scope.shareUserLabel = $scope.currentCustomer.users[0].empname + '等';
          }
          $scope.currentCustomer.hasLoadShareInfo = true;
        });
      }
    };
    $scope.setIsGlobal = function () {
      CustomersService.setIsGlobal($scope.currentCustomer.cid, $scope.currentCustomer.isGlobal, function (data) {
        if (!data.result && data.result == 0) {
          $scope.currentCustomer.isGlobal = $scope.currentCustomer.isGlobal == '1' ? '0' : '1';
        }
      });
    };
    $scope.delete = function () {
      CustomersService.deleteCustomer($scope.currentCustomer, function () {
        CommonUtils.goBackTo('tab.cus');
      }, function () {
        CommonUtils.showToast('删除客户失败');
      });
    };
    $scope.setMainCard = function (card) {
      if ($scope.currentCustomer.cardId == card.id) {
        alert('此名片已经是默认名片了');
      } else {
        CustomersService.setMainCard($scope.currentCustomer.cid, card.id, function () {
          $scope.currentCustomer.cardId = card.id;
          $scope.currentCustomer.cname = card.cname;
          $scope.currentCustomer.duty = card.duty;
          $scope.currentCustomer.company = card.company;
          $scope.currentCustomer.website = card.website;
          $scope.currentCustomer.phone = card.phone;
          $scope.currentCustomer.tel = card.tel;
          $scope.currentCustomer.fax = card.fax;
          $scope.currentCustomer.email = card.email;
          $scope.currentCustomer.address = card.address;
        });
      }
      $ionicListDelegate.closeOptionButtons();
    };
    $scope.deleteCard = function (card) {
      if ($scope.currentCustomer.cardId == card.id) {
        alert('无法删除默认名片');
      } else {
        CustomersService.delCard(card.id, function (index) {
          $scope.currentCustomer.cards.splice(index, 1);
        });
      }
    };
    $scope.selectUser = function () {
      CommonUtils.goTo('selectUser');
    };
  })
  .controller('EditCardCtrl', function ($scope, $state, CustomersService, CommonUtils, $ionicNavBarDelegate) {
    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.currentCustomer = CustomersService.getCurrentCustomer();
      $scope.currentCard = CustomersService.getCurrentCard();
      $scope.titleName = $scope.currentCustomer.cid ? '编辑名片' : '新建客户';
      if (!$scope.currentCustomer.id) {
        $scope.departmentLabel = '';
        $scope.shareUserLabel = '';
        $scope.getShareInfo();
      }
    });
    $scope.$on('$ionicView.afterEnter', function () {
      $ionicNavBarDelegate.title($scope.titleName);
    });
    $scope.goSharePer = function () {
      action = "sharePer";
      $state.go('contacts', {action: JSON.stringify(action)});
    };
    $scope.goShareDep = function () {
      action = "shareDep";
      $state.go('Orgs', {action: JSON.stringify(action)});
    };
    $scope.addOrUpdateCard = function () {
      var tmp = {
        isGlobal: $scope.currentCustomer.isGlobal,
        userid: $scope.currentCustomer.userid,
        users: [],
        departments: [],
        cards: [$scope.currentCard]
      };
      CustomersService.addOrUpdateCard(tmp, $scope.currentCustomer.users, $scope.currentCustomer.departments, function (data) {
        //如果请求返回的客户ID和名片ID不为空即在数据库内创建成功
        if (data.customerId && data.cardId) {
          var dt = new Date('yyyy-MM-dd');
          //如果名片数量为0,即表示这个客户是新建的客户
          if ($scope.currentCustomer.cards.length == 0) {
            //将新建的资料绑定到当前的currentCustomer
            $scope.currentCustomer.remark = $scope.currentCard.remark;
            $scope.currentCustomer.dt = dt;
            $scope.currentCard.dt = dt;
            $scope.currentCard.id = data.cardId;
            $scope.currentCustomer.cards.push($scope.currentCard);
            $scope.currentCustomer.id = data.customerId;
            $scope.currentCustomer.cid = data.customerId;
            $scope.currentCustomer.cardId = data.cardId;
            $scope.currentCustomer.cname = $scope.currentCard.cname;
            $scope.currentCustomer.duty = $scope.currentCard.duty;
            $scope.currentCustomer.company = $scope.currentCard.company;
            $scope.currentCustomer.website = $scope.currentCard.website;
            $scope.currentCustomer.phone = $scope.currentCard.phone;
            $scope.currentCustomer.tel = $scope.currentCard.tel;
            $scope.currentCustomer.fax = $scope.currentCard.fax;
            $scope.currentCustomer.email = $scope.currentCard.email;
            $scope.currentCustomer.address = $scope.currentCard.address;
            CustomersService.addCustomer($scope.currentCustomer);
            CommonUtils.showToast('新建客户成功');
            CommonUtils.goBack();
          } else {
            $scope.currentCard.dt = dt;
            $scope.currentCustomer.cards.push($scope.currentCard);
            CommonUtils.showToast('新建名片成功');
            CommonUtils.goBack();
          }
        } else {
          CommonUtils.showToast('新建失败', 1500);
        }
      });
    };
    $scope.getShareInfo = function () {
      if ($scope.currentCustomer.departments) {
        $scope.departmentLabel = $scope.currentCustomer.departments[0].orgname + '等';
      }
      if ($scope.currentCustomer.users) {
        $scope.shareUserLabel = $scope.currentCustomer.users[0].empname + '等';
      }
    };
    $scope.isFormDisabled = function () {
      if ($scope.formScope) {
        return $scope.formScope.cardForm.$invalid;
      } else {
        return true
      }
    };
    $scope.setFormScope = function (scope) {
      $scope.formScope = scope;
    };
  })
  .controller('SingleUserCtrl', function ($scope, CustomersService, CommonUtils, $ionicModal) {
    var selectDeps = [];
    /**
     * 获取用户列表
     */
    CustomersService.getAllUsers(function (data) {
      if (data.users) {
        $scope.users = data.users;
      }
    });

    $ionicModal.fromTemplateUrl('templates/department_modal.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function (modal) {
      $scope.modal = modal;
    });

    $scope.openModal = function () {
      CustomersService.queryAllOrg(function (data) {
        $scope.modal.show();
        //$scope.show = $scope.data;
        $scope.deps = data.OrgName;
      });
    };
    $scope.closeModal = function (save) {
      if (save) {
        $scope.groupkeyword = [];
        angular.forEach(selectDeps, function (dep, index) {
          $scope.groupkeyword.push(dep.orgid);
        });
      }
      $scope.modal.hide();
    };
    $scope.$on('$destroy', function () {
      $scope.modal.remove();
    });
    $scope.selectAllDep = function (statue) {
      selectDeps = [];
      if (statue == true) {
        angular.forEach($scope.deps, function (dep, index) {
          selectDeps.push({'orgid': dep.orgid});
        });
      }
    };
    $scope.checkedDep = function (orgid) {
      for (var i = 0; i < selectDeps.length; i++) {
        if (selectDeps[i].orgid == orgid) {
          return true;
        }
      }
      return false;
    };
    $scope.selectDep = function (orgid, statue) {
      if (statue) {
        selectDeps.push({'orgid': orgid})
      } else {
        var index = selectDeps.indexOf(orgid);
        if (index > -1) {
          selectDeps.splice(index, 1);
        }
      }
    };
    $scope.giveToUser = function (user) {
      CustomersService.giveToUser(user, function () {
        CommonUtils.goBackTo('tab.cus');
      });
    }
  })
  .controller('LocationCtrl', function ($scope, CustomersService, $timeout, CommonUtils) {
    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.currentCustomer = CustomersService.getCurrentCustomer();
    });
    $scope.showLocation = function (address) {
      var h1 = document.getElementsByTagName('ion-content')[0].clientHeight;
      var h2 = document.getElementsByTagName('ion-tabs')[0].children[0].clientHeight;
      var height = h1 + h2;
      angular.element(document.getElementById('allMap')).css('height', height + 'px');
      var map = new BMap.Map("allMap");
      map.addControl(new BMap.ZoomControl());
      // 创建地址解析器实例
      var myGeo = new BMap.Geocoder();
      var myGeolocation = new BMap.Geocoder();
      // 将地址解析结果显示在地图上,并调整地图视野
      myGeo.getPoint(address, function (point) {
        if (point) {
          map.centerAndZoom(point, 16);
          map.addOverlay(new BMap.Marker(point));
        } else {
          alert('无法解释位置:' + address);
          myGeolocation.getCurrentPosition(function (result) {
            map.centerAndZoom(result.point, 16);
            map.addOverlay(new BMap.Marker(result.point));
          });
        }
      }, "");
    };
  });
